package pt.fct.mpc.lastfm.album;

import java.util.List;
import java.util.Vector;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class TracksXmlHandler extends DefaultHandler{

	private List<TrackData> tracks = new Vector<TrackData>();
	private TrackData trackDataSet = null;
	private String position = "";

	public List<TrackData> getParsedData() {
		return this.tracks;
	}

	public void startDocument() throws SAXException {
		this.trackDataSet = new TrackData();
	}

	public void endDocument() throws SAXException {
		// Nothing to do
	}

	/** Gets be called on opening tags like:
	 * <tag>
	 * Can provide attribute(s), when xml was like:
	 * <tag attribute="attributeValue">*/
	public void startElement(String namespaceURI, String localName,
			String qName, Attributes atts) throws SAXException {
		position = position.concat("." + localName);
		if (localName.equals("track")) {
			trackDataSet = new TrackData();
		}
	}

	/** Gets be called on closing tags like:
	 * </tag> */
	public void endElement(String namespaceURI, String localName, String qName)
	throws SAXException {
		if (localName.equals("track")) {
			tracks.add(trackDataSet);
		}
		position = position.substring(0, position.lastIndexOf("." + localName));
	}

	/** Gets be called on the following structure:
	 * <tag>characters</tag> */
	public void characters(char ch[], int start, int length) {
		if(position.compareTo(".lfm.playlist.trackList.track.title")==0){
			trackDataSet.setName(new String(ch, start, length));
		} else if(position.compareTo(".lfm.playlist.trackList.track.duration")==0){
			trackDataSet.setDuration(new String(ch, start, length));
		} 
	}
}